<?php

namespace app\admin\controller;

use app\admin\model\AdminUser;
use app\admin\model\Member;

use think\facade\Request;
use think\facade\Session;


class Index extends Base
{

    public function initialize()
    {
        if (Session::get('username') == '') {
            $this->error("请先登录", 'base/login');
        }
    }

    /**
     * 首页
     * @return mixed
     */
    public function index()
    {
        return $this->managerList();
    }

    public function memLst()
    {
        $list = Member::paginate(20)->order('m_id desc');
        $this->assign('list', $list);
        return $this->fetch();
    }

    /**
     * 管理员列表
     * @return mixed
     */
    public function managerList()
    {
        $query = AdminUser::select();
        $this->assign("list", $query);
        return $this->fetch("managerList");
    }

    public function addManager()
    {
        return $this->fetch("addManager");
    }

    public function addManagerRe()
    {
        $data = Request::param();
        if ($data['pass'] != $data['pass2']) {
            $this->error("密码输入不一致", 'addManager');
        } else {
            unset($data['pass2']);
            $data['pass'] = md5(md5($data['pass']));
        }
        $seladmin = AdminUser::where('username', $data['username'])->select();
        if (count($seladmin) >= 1) {
            $this->error("用户名" . $data['username'] . "已存在", 'addManager');
        }
        $admin = new AdminUser();
        $admin->save($data);
        $this->redirect('managerList');
    }

    public function managerUp()
    {
        $admin = AdminUser::find(Request::get('id'));
        $this->assign("admin", $admin);
        return $this->fetch("managerUp");
    }

    public function managerUpSave()
    {
        $data = Request::param();
        if ($data['pass'] != $data['pass2']) {
            $this->error("密码输入不一致", 'managerUp?id=' . $data['id']);
        } else {
            unset($data['pass2']);
            $data['pass'] = md5(md5($data['pass']));
        }
        $admin = new AdminUser();
        if ($admin->update($data)) {
            $this->success("修改成功", 'managerList');
        } else {
            $this->error("修改失败", 'managerList');
        }

    }


    public function managerDel()
    {
        $admin = AdminUser::get(Request::param('id'));
        if ($admin->delete()) {
            $this->redirect('managerList');
        }
    }

    /**
     * 用户充值余额数据
     * @return void
     */
    public function ajaxMemInfo(){
        $mem=Member::find(Request::param('id'));
        echo json_encode($mem);
    }

    public function balanceUp(){
        $data=Request::param();
        if(Member::update($data)){
            $this->redirect('memlst');
        }else{
            $this->error('充值异常','memlst');
        }
    }

}
